package com.game.spacetrader.TradeGoods;

import java.util.ArrayList;

import com.game.spacetrader.Game;
import com.game.spacetrader.R;
import com.game.spacetrader.map.MapView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

/**
 * Class for the hull tab
 */
public class TradeGoodsHull extends Activity {
	/**
	 * Handles ListView and ListView events
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tradegoodslist);
		ListView hullList = (ListView) findViewById(R.id.tradeList);
		final TextView playerPoints = (TextView) findViewById(R.id.playerPointsTV);
		playerPoints.setText("Points: " +  Game.getInstance().getPlayer().getPoints()+"\nCargo: "+Game.getInstance().getPlayer().getCargoSize()+"/"
				+Game.getInstance().getPlayer().getMaxCargo()+"\nGas: "+Game.getInstance().getPlayer().getGas()+"\nPlanet: " + Game.getInstance().getCurrentPlanet().getName() + "\nCondition: "
				+" "+Game.getInstance().getCurrentPlanet().getEvent().getEvent());
		
		final ArrayList<TradeGoods> market = Game.getInstance().getPlayer().getCargo();
		final ArrayList<String> listString = new ArrayList<String>();
		for(TradeGoods i: market)
			listString.add(i.toString() + "\n - Price: " + i.price() + "\n - Quantity: " + i.getQuantityHave());
        final ArrayAdapter<String> arrayAdapter =      
        new ArrayAdapter<String>(this,R.layout.tradegoodslistcolor, listString);
        hullList.setAdapter(arrayAdapter); 
		
		hullList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			/**
			 * Called when item on list is selected
			 */
			public void onItemClick(AdapterView<?> arg0, View v, int index,
					long id) {
				
				final TextView view = (TextView) v;
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(arg0.getContext());
					alertDialogBuilder.setTitle("Market");
					
					LayoutInflater inflater = getLayoutInflater();
					
				    final View alertView = inflater.inflate(R.layout.tradegoodsalert, null);
				    ((TextView) alertView.findViewById(R.id.textView2)).setText("0 " + market.get(listString.indexOf(view.getText())) + "s Selected");
				    final SeekBar bar = (SeekBar) alertView.findViewById(R.id.seekBar1);
				  
				    /*Sets size of bar to quantity available or space available in hull*/
				    int max = Game.getInstance().getPlayer().getCargo().get(index).getQuantityHave();
				    bar.setMax(max);
				    bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
				    	/**
				    	 * Adjusts number of items shown when seekbar moved
				    	 */
						public void onProgressChanged(SeekBar seekBar,
								int progress, boolean fromUser) {
							((TextView) alertView.findViewById(R.id.textView2)).setText("" + progress + " " + market.get(listString.indexOf(view.getText())) + "s Selected");
							Game.getInstance().getPlayer().getCargo().get(listString.indexOf(view.getText())).setQuantity(progress);
						}

						public void onStartTrackingTouch(SeekBar seekBar) {
							// TODO Auto-generated method stub
							
						}

						public void onStopTrackingTouch(SeekBar seekBar) {
							// TODO Auto-generated method stub
							
						}
				    	
				    });
				    
					alertDialogBuilder.setTitle("Hull");					
					alertDialogBuilder
						.setMessage("How many " + market.get(listString.indexOf(view.getText())) + "s do you want to sell?")
						.setCancelable(false)
						.setPositiveButton("Confirm",new DialogInterface.OnClickListener() {
							/**
							 * Sells item, adds points, adds to market, removes from hull, refreshes screen
							 */
							public void onClick(DialogInterface dialog,int id) {
									TradeGoods good = market.get(listString.indexOf(view.getText()));
									int have = Game.getInstance().getPlayer().getCargo().get(listString.indexOf(view.getText())).getQuantityHave();
									int sold = Game.getInstance().getPlayer().getCargo().get(listString.indexOf(view.getText())).getQuantity();
									int pointsHave =  Game.getInstance().getPlayer().getPoints();
									int PointsEarned = sold*good.getPrice();
									int left = have - sold;
									
									Game.getInstance().getPlayer().getCargo().get(listString.indexOf(view.getText())).setQuantityHave(left);
									Game.getInstance().getPlayer().setPoints(pointsHave+PointsEarned);
									Game.getInstance().getPlayer().subCargoSize(bar.getProgress());
									
									TradeGoodsAdaptor.goods.get(listString.indexOf(view.getText())).setQuantityHave(TradeGoodsAdaptor.goods.get(listString.indexOf(view.getText())).getQuantityHave() + sold);
									arrayAdapter.notifyDataSetChanged();
									listString.clear();
									for(TradeGoods i: market)
										listString.add(i.toString() + " - Price: " + i.price() + " - Quantity: " + i.getQuantityHave());
									playerPoints.setText("Points: " +  Game.getInstance().getPlayer().getPoints()+" ...Cargo: "+Game.getInstance().getPlayer().getCargoSize()+"/"
											+Game.getInstance().getPlayer().getMaxCargo());
								}
							  })
							.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
								/**
								 * Closes window
								 */
								public void onClick(DialogInterface dialog,int id) {
									dialog.cancel();
								}
							});
							final AlertDialog alertDialog = alertDialogBuilder.create();
							alertDialog.setView(alertView);
							alertDialog.show();
				} 
		});
	}
	
	/**
	 * Called to start AlertDialog. String passed in is message for dialog
	 * 
	 * @param string
	 */
	public void failDialog(String string) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(TradeGoodsHull.this);
		alertDialogBuilder.setTitle("Error");
			
		alertDialogBuilder
			.setMessage(string)
			.setCancelable(false)
			.setPositiveButton("Okay",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					dialog.cancel();
				}
		  });
	      AlertDialog alertDialog = alertDialogBuilder.create();
		  alertDialog.show();
	}
	
	/**
	 * Creates option menu
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_space_trader, menu);
	    return true;
	}
	
	/**
     * Listener for the options menu
     * @param item the item in the Menu that is clicked
     */
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.travel:
	        	Intent i = new Intent(this, MapView.class);
	        	startActivity(i);
	            return true;
	        case R.id.market:
	        	Intent i2 = new Intent(this, TradeGoodsView.class); startActivity(i2);
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
}